<?php
//自动生成,请根据需要修改
namespace app\user\controller;

use app\common\controller\Base;

ini_set("display_errors", "on");

use think\facade\Env;

require_once Env::get('extend_path') . 'aliyun/aliyun-dysms-php-sdk/api_sdk/vendor/autoload.php';

use Aliyun\Core\Config;
use Aliyun\Core\Profile\DefaultProfile;
use Aliyun\Core\DefaultAcsClient;
use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\SendBatchSmsRequest;
use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
use think\Validate;
use think\Db;

// 加载区域结点配置
Config::load();

/**
 * @title 验证码页面（模块01-02）
 * @description 验证码说明
 * @group 用户中心（01）
 * @header name:model_id require:0 default:01-02 desc:模块
 * @groupremark 已使用错误码：1-01-02-0001 校验失败 1-01-02-0002 添加失败 1-01-02-0003 编辑校验失败 1-01-02-0004 编辑失败 1-01-02-0005 获取详情失败  1-01-02-0006 获取列表失败 1-01-02-0007获取单个详情失败 1-01-02-0008 删除失败
 */
class VerificationCode extends Base
{
    static $acsClient = null;

    //测试
    public function test()
    {

        return 'test 111';
    }

    /**
     * @title 添加验证码
     * @description 添加验证码
     * @author 李锐志
     * @url /user/verification_code/add
     * @method *
     *
     * @header name:token require:1 default: desc:token
     *
     * @return data:验证码@!
     * @data
     * @return error_id:1-01-02-0001 校验失败  1-01-02-0002 添加失败
     */
    public function add()
    {
        $data = input();
        /**
         *$validate = new \app\user\validate\VerificationCode();
         *$validate->scene('add');
         *$result = $validate->batch(true)->check($data);
         *if ($result !== true) {
         *$msg['msg']='校验失败';
         *$msg['validate']=$validate->getError();
         *$msg['error_id']='1-01-02-0001';
         *return $this->errorJson($msg);
         *}
         **/
        $model = new \app\user\model\VerificationCode();
        $flag = $model->save($data);
        if ($flag) {
            $msg['msg'] = '添加成功';
            $msg['data'] = $model->get($model['id']);
            return $this->successJson($msg);
        } else {
            $msg['error_id'] = '1-01-02-0002';
            $msg['msg'] = '添加失败';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 编辑验证码
     * @description 编辑验证码
     * @author 李锐志
     * @url /user/verification_code/edit
     * @method *
     *
     * @header name:token require:1 default: desc:token
     *
     * @return data:验证码@!
     * @data
     * @return error_id:1-01-02-0003 校验失败 1-01-02-0004 修改失败
     */
    public function edit()
    {
        $data = input();
        $validate = new \app\user\validate\VerificationCode();
        $validate->scene('edit');
        $result = $validate->batch(true)->check($data);
        if ($result !== true) {
            $msg['msg'] = '校验失败';
            $msg['validate'] = $validate->getError();
            $msg['error_id'] = '1-01-02-0003';
            return $this->errorJson($msg);
        }
        $model = new \app\user\model\VerificationCode();
        $flag = $model->edit($data);
        if ($flag !== false) {
            $msg['msg'] = '修改成功';
            $msg['data'] = $model->get($data['id']);
            return $this->successJson($msg);
        } else {
            $msg['error_id'] = '1-01-02-0004';
            $msg['msg'] = '修改失败';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 删除验证码
     * @description 删除验证码
     * @author 李锐志
     * @url /user/verification_code/delete
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @param name:id type:int|array require:1 other: desc:要删除的id
     * @return error_id:1-01-02-0008 删除失败
     */
    public function delete()
    {
        $id = input('id');
        $model = new \app\user\model\VerificationCode();
        $flag = $model->destroy($id);
        if ($flag) {
            $msg['msg'] = '删除成功';
            return $this->successJson($msg);
        } else {
            $msg['msg'] = '删除失败';
            $msg['error_id'] = '1-01-02-0008';
            return $this->errorJson($msg);
        }
    }

    /**
     * @title 单个查询验证码
     * @description 单个查询验证码
     * @author 李锐志
     * @url /user/verification_code/info
     * @method *
     *
     * @param name:token require:1 default: desc:token
     *
     * @return data:验证码@!
     * @data
     * @return error_id:1-01-02-0005 校验失败 1-01-02-0007 获取失败
     */
    public function info()
    {
        $model = new \app\user\model\VerificationCode();
        $Fields = $model->getTableFields();
        $data = \think\facade\Request::only($Fields);
        /**
         *$validate = new \app\user\validate\VerificationCode();
         *$validate->scene('info');
         *$result = $validate->batch(true)->check($data);
         */
        if (!$data) {
            $msg['msg'] = '必须有参数';
            $msg['error_id'] = '1-01-02-0005';
            return $this->errorJson($msg);
        }
        $model = new \app\user\model\VerificationCode();
        $info = $model->where($data)->find();
        if ($info) {
            $msg['msg'] = '获取成功';
            $msg['data'] = $info;
            return $this->successJson($msg);
        } else {

            $msg['msg'] = '获取失败';
            $msg['error_id'] = '1-01-02-0007';
            return $this->successJson($msg);
        }
    }

    /**
     * @title 查询列表验证码
     * @description 查询列表验证码
     * @author 李锐志
     * @url /user/verification_code/get_list
     * @method *
     * @param name:token require:1 default: desc:token
     * @param name:page require:1 default: desc:第几页
     * @param name:pagesize require:1 default: desc:每页数
     * @return list:验证码@
     * @list
     * @return error_id:1-01-02-0006 校验失败
     */
    public function get_list()
    {
        $model = new \app\user\model\VerificationCode();
        $Fields = $model->getTableFields();
        $data = \think\facade\Request::only($Fields);
        /**
         *$validate = new \app\user\validate\VerificationCode();
         *$validate->scene('lists');
         *$result = $validate->batch(true)->check($data);
         *if ($result !== true) {
         *$msg['msg']='校验失败';
         *$msg['validate']=$validate->getError();
         *$msg['error_id']='1-01-02-0006';
         *return $this->errorJson($msg);
         *}
         **/
        $list = $model->where($data)->paginate();
        $msg['list'] = $list;
        return $this->successJson($msg);
    }

    /**
     * @title 前台发送短信
     * @description 接口说明
     * @author 李锐志
     * @url /user/verification_code/code
     * @method get
     * @param name:mobile type:int require:0 default:0 other: desc:手机号码
     * @param name:code_type type:varchar require:0 default:0 other: desc:验证码类型(register:注册,update_password:更新密码)
     */
    //验证码
    public function code()
    {
        $data = input();
        $validate = new Validate([
            'mobile' => 'require',
            'code_type' => 'require|in:register,update_password'
        ], [
            'mobile' => '手机号码不能为空',
            'code_type.require' => '验证码类型不能为空',
            'code_type.in' => '验证码类型不正确',
        ]);

        if (!$validate->check($data)) {
            $msg['msg'] = $validate->getError();
            return $this->errorJson($msg);
        }
        $nowTime = $_SERVER['REQUEST_TIME'];
        //时间
        $time = 1 * 60;
        $old = Db::name('verification_code')
            ->where('create_time', ">", $nowTime - $time)
            ->where('mobile', $data['mobile'])
            ->where('code_type', $data['code_type'])
            ->find();

        if ($old) {
            $msg['msg'] = "最近已发送(1分钟)";
            $msg['data'] = "最近已发送";
            return $this->errorJson($msg);
        }
        $verify = rand(1111, 9999);//随机生成

        //调用发送短信
        $acsResponse = $this::sendSms($data['mobile'], $verify);

        //要插入的数据
        $argv['mobile'] = $data['mobile'];          //手机号
        $argv['sign'] = '李锐志';                   //签名名称
        $argv['code'] = $verify;                   //验证码
        $argv['create_time'] = $nowTime;           //发送时间
        $argv['code_type'] = $data['code_type'];   //验证码类型
        $argv['over_time'] = $nowTime + 600;//10分钟时间
        if ($acsResponse->Code == 'OK') {
            Db::name('verification_code')->insertGetId($argv);
            $msg['msg'] = "已发送";
            return $this->successJson($msg);
        } else {
            $msg['msg'] = $acsResponse;
            return $this->errorJson($msg);
        }
    }

    /**
     * 取得AcsClient
     *
     * @return DefaultAcsClient
     */
    public static function getAcsClient()
    {
        //产品名称:云通信流量服务API产品,开发者无需替换
        $product = "Dysmsapi";

        //产品域名,开发者无需替换
        $domain = "dysmsapi.aliyuncs.com";

        // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
        $accessKeyId = "LTAI5sR7ymmku3tr"; // AccessKeyId

        $accessKeySecret = "IbleGekKjsGdvDnJzdXOc0nhZDuHKY"; // AccessKeySecret

        // 暂时不支持多Region
        $region = "cn-hangzhou";

        // 服务结点
        $endPointName = "cn-hangzhou";


        if (static::$acsClient == null) {

            //初始化acsClient,暂不支持region化
            $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);

            // 增加服务结点
            DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);

            // 初始化AcsClient用于发起请求
            static::$acsClient = new DefaultAcsClient($profile);
        }
        return static::$acsClient;
    }

    /**
     * 发送短信
     * @return stdClass
     */
    public static function sendSms($mobile, $verify)
    {

        // 初始化SendSmsRequest实例用于设置发送短信的参数
        $request = new SendSmsRequest();

        //可选-启用https协议
        //$request->setProtocol("https");

        // 必填，设置短信接收号码
        $request->setPhoneNumbers($mobile);

        // 必填，设置签名名称，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
        $request->setSignName("李锐志");

        // 必填，设置模板CODE，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $request->setTemplateCode("SMS_139239087");

        // 可选，设置模板参数, 假如模板中存在变量需要替换则为必填项
        $request->setTemplateParam(json_encode(array(  // 短信模板中字段的值
            "code" => $verify,
        ), JSON_UNESCAPED_UNICODE));

        // 发起访问请求
        $acsResponse = static::getAcsClient()->getAcsResponse($request);

        return $acsResponse;
    }


    /**
     * @title 检查验证码数据
     * @description 检查验证码数据
     * @author 李锐志
     * @url /user/verification_code/check
     * @method
     * @param name:mobile type:int require:0 default:0 other: desc:手机号码
     * @param name:code type:int require:0 default:0 other: desc:验证码
     * @param name:code_type type:varchar require:0 default:0 other: desc:验证码类型
     */
    public function check()
    {
        $data = input();
        $lastCode = Db::name('verification_code')->strict(false)->where($data)->find();
        if(!$lastCode){
            $msg['msg'] = '验证码错误!';
            return $this->errorJson($msg);
        }
        //进行时间的校对
        if ($lastCode['over_time'] < time()) {
            $msg['msg'] = '验证码已经过期!';
            $msg['check'] = false;
            return $this->errorJson($msg);
        }
        //进行数据比较
        if ($data['code'] == $lastCode['code']) {
            $msg['msg'] = '校验成功!';
            Db::name('verification_code')->strict(false)->where($data)->delete();
            return $this->successJson($msg);
        }
    }
}
